package com.demo.boss.tools;

import com.demo.boss.common.mail.Attachment;
import com.demo.boss.common.mail.MailProperty;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.List;

@Component
public class MailUtil {
    @Resource
    private JavaMailSender mailSender;
    public boolean sendSimpleMail(MailProperty property){
        boolean flag = false;
        try {
            // 创建邮件对象
            SimpleMailMessage message = new SimpleMailMessage();
            // 设置邮件的基本消息： 发送者 接收者 邮件主题 邮件正文
            message.setFrom(property.getFrom());
            message.setTo(property.getTo());
            message.setSubject(property.getSubject());
            message.setText(property.getText());
            // 发送邮件
            mailSender.send(message);
            flag = true;
        } catch (MailException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public boolean sendAestAttachFile(MailProperty property){
        boolean flag = false;
        try {
            // 创建 MimeMessage
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            // 通过 MineMessageHelper类，辅助设置，发送者， 接收者，邮件主题 邮件正文  true :是否附件
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(property.getFrom());
            mimeMessageHelper.setTo(property.getTo());
            mimeMessageHelper.setSubject(property.getSubject());
            mimeMessageHelper.setText(property.getText());

            // 附件（可以多个）
            List<Attachment> attachemtList = property.getAttachemtList();
            for (Attachment attachment : attachemtList) {
                mimeMessageHelper.addAttachment(attachment.getName(),attachment.getFile());
            }
            mailSender.send(mimeMessageHelper.getMimeMessage());
            flag = true;
        } catch (MailException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }
}
